<?php

class AgentsController extends Zend_Controller_Action {

    protected $_log;
    protected $doctrineContainer;
    #   protected $_translate;

    public function init() {
        $this->_log = Zend_Registry::get('log');
        $this->doctrineContainer = Zend_Registry::get('doctrine');
        #    $this->_translate = $this->view->translate;
    }

    public function indexAction() {
        $this->view->headTitle($this->view->translate->_('Agents'), 'PREPEND');
        /*
         * @todo: implement all the Agents database model and pick it in here
         */

        $em = $this->doctrineContainer->getEntityManager();
        $agents = $em->getRepository('Jhub1db\Entity\Jhub1agent')->getAllOrdered();
        #->findBy(array('visible' => 0))
        $this->view->agents = $agents;
        /*
          if($agents) {
          foreach($agents as $agent) {


          echo 'Found an Entity\User: ' . PHP_EOL
          . $agent->getId() . ' => ' . $agent->getInstalled() . '(' . get_class($agent) . ')' . PHP_EOL
          . 'and ' . ' Entity\Comment attached to it: ' . PHP_EOL;
          #     foreach($agent->getDevrecords() as $comment) {
          #         echo $comment->getIfType();
          #          echo '  ' . $comment->getId() . ' => ' . $comment->getContent()
          #              . ' (' . get_class($comment) . ')' . PHP_EOL;
          #     }
          #. $agent->getDevrecords()->count()
          }
          }
          #    var_dump($agents);
          #  die;

         */
    }

    public function listAction() {
        $this->view->headTitle('LoggedIn', 'PREPEND');
    }

    public function detailsAction() {
        $aid = $this->_getParam('aid');
        if ($aid > 0) {
            $this->view->headTitle($this->view->translate->_('Agent details'), 'PREPEND');
            $em = $this->doctrineContainer->getEntityManager();
            $agentsHubs = $em->getRepository('Jhub1db\Entity\Jhub1agentdev')->findAll();
            $this->view->agentsHubs = array();
            foreach ($agentsHubs as $dev) {
               if($dev->getAgent()->getId() == $aid) {
                   $this->view->agentsHubs[] = $dev;
               }
            }
            #$this->view->agentsHubs = $agentsHubs;
            /**
             * @todo: implement all the Agents database model and pick Agent details in here
             */
        } else {
            $this->_redirect("agents/index");
        }
    }

    public function addAction()
    {
        $em = $this->doctrineContainer->getEntityManager();
        $this->view->headTitle($this->view->translate->_('Install new agent'), 'PREPEND');
        $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'production');
       # $packagesPath = $config->agent->packages->folder;
        $assetsFolder = "/opt/jhub1/interfaces/FrontEnd/public/assets/packages";
        
        
        $packages = new Application_Model_Packages($config->agent->packages->folder, $assetsFolder);
        
        
        
        
        
   /*     
        $command = "ls -1 $packagesPath | grep tar.gz";
        exec($command, $lines);
        $result = array();
        foreach($lines as $package) {
              $packagePath = $packagesPath . "/" . $package;
              ob_start();
              system("tar xf $packagePath agent-manifest.xml --to-stdout");
              $manifest = ob_get_contents();
              ob_end_clean(); 
    * 
    */          
         /*
         * @todo: make sure that this is manifest before proceding
         */
              #$manifest = <<<EOT#$manifest#EOT;
              #$manifestArr = array();
              #$result = array();
        /*
              try {
                $manifestXML = new Zend_Config_Xml($manifest);
                $manifestArr = $manifestXML->toArray();
                $manifestArr['packagename'] = $package;
                $agent = $em->getRepository('Jhub1db\Entity\Jhub1agent')->findBy(array('uaid' => $manifestArr['agent']['id']));
                if(count($agent)) {
                    $manifestArr['installed'] = $agent[0]->getInstalled();
                    $manifestArr['installedversion'] = $agent[0]->getVersion();
                }
                array_push($result, $manifestArr);
              } catch (Exception $e) {
                    echo 'ERROR: ' . $e->getMessage() . ' FOR PACKAGE: ' . $package;
              }
              #create dir
              #mkdir -p /home/marek/Desktop/dd/dds
              #extract images
              #tar xf adahgfgad-noop04.tar.gz -C /home/marek/Desktop agent-manifest.xml
              $assetsdir = "/opt/jhub1/interfaces/FrontEnd/public/assets/packages/" . $manifestArr['agent']['id'];
                            
         * 
         */
             //
   #           $manifestXML = new Zend_Config_Xml($manifest);
    #          $manifestArr = $manifestXML->toArray();
     #         $manifestArr['package'] = $package;
      #        $agent = $em->getRepository('Jhub1db\Entity\Jhub1agent')->findBy(array('uaid' => $manifestArr['id']));
       #       if(count($agent)) {
        #          $manifestArr['installed'] = $agent[0]->getInstalled();
         #         $manifestArr['installedversion'] = $agent[0]->getVersion();
          #    }
           #   array_push($result, $manifestArr);
      #  }
      #  var_dump($result);
     #   $this->view->packages = $result;
        $this->view->packageObjArray = $packages;
    }
    
    public function actionsAction()
    {
        $this->_helper->layout()->disableLayout();
        $this->getHelper('viewRenderer')->setNoRender();
        
        $action     = $this->_getParam('doaction');
        $agentids   = $this->_getParam('agentid');
        $agentItems = count($agentids);
        if (preg_match("/^(hide|show|uninstall)/", $action) && $agentItems > 0) {
            $em = $this->doctrineContainer->getEntityManager();            
            if ($action == "hide") {
                foreach($agentids as $agentid) {
                     $agent = $em->getRepository('Jhub1db\Entity\Jhub1agent')->findBy(array('id' => $agentid));
                     $agent[0]->setVisible(0);
                     $em->persist($agent[0]);    
                }
            } else if ($action == "show") {
                foreach($agentids as $agentid) {
                     $agent = $em->getRepository('Jhub1db\Entity\Jhub1agent')->findBy(array('id' => $agentid));
                     $agent[0]->setVisible(1);
                     $em->persist($agent[0]);    
                }                
            } else if ($action == "uninstall") {
                foreach($agentids as $agentid) {
                     $agent = $em->getRepository('Jhub1db\Entity\Jhub1agent')->findBy(array('id' => $agentid));
                     $em->remove($agent[0]);
            /**
             * @todo: implement validation before delete chain is triggered 
             */
                }                
            } else {
                $this->_redirect("agents/index");                
            }
            $em->flush();            
        } else {
           $this->_redirect("agents/index"); 
        }        
        $this->_redirect("agents/index");
    }

}

